"""

Computational Economics
04: Conditionals
http://johnstachurski.net/lectures/conditionals.html

"""


import math, random


"""
    Problem 1:

        * In one line, count the number of even numbers in 0,...,99
              o Hint: x % 2 returns 0 if x is even, 1 otherwise
              o Use a list comprehension and sum()
"""
even_nums = sum([1 for n in range(100) if not n % 2])
print 'num of even nums between 0 and 99: %s' % (even_nums)


"""
    Problem 2:

        * In one line, count the number of 'd's in S = 'the good, the bad and the ugly'
              o That is, write S.count('d') a different way
"""
S = 'the good, the bad and the ugly'
d_count = sum([1 for c in S if c == 'd'])
print "d's in %s: %s" % (S, d_count)
assert S.count('d') == d_count


"""
    Problem 3:

        * Given X = ((2, 5), (4, 2), (9, 8)), count number of pairs which are both even
              o That is, count num of (a,b) such that a is even and b is even
"""
X = ((2, 5), (4, 2), (9, 8))
even_pairs = sum([1 for t in X if not t[0] % 2 and not t[1] % 2])
print 'num of even pairs in %s: %s' % (X, even_pairs)


"""
    Problem 4:

    The next problem is a bit harder, and requires you to write a script

    Suppose that Y counts the number of successes in n trials with success probability p

        * E.g., the number of heads in 10 coin flips (trials) when the probability of heads (success) = 0.5

    Then Y is said to have the binomial distribution, and we write Y ~ Bin(n, p)

    We can simulate one trial by with success probability p by

        * drawing U from the uniform distribution on [0,1]
        * reporting whether U < p (success) or not (failure)
              o In this case, the probability of success is p (think about it)

    Your exercise is to

    Simulate a draw of Y ~ Bin(n, p) using uniform random variables

        * Get n and p from the user
        * Hint: Use a list comprehension
"""
print """

This exercise simulate a trial in which you determine the number of trials and
the probability of success for each trial.

"""
prompt = 'Input the number of trials: '
n = int(raw_input(prompt))

prompt = 'What is the % chance of success (1-99): '
p = float('%.2f' % (float(raw_input(prompt)) / 100))

successes = sum([1 for r in range(n) if (random.uniform(0, 1) < p)])
print 'num of trial successes (n=%s, p=%s): %s' % (n, p, successes)



print '%s: ok' % (__file__)
